package com.kuangjia.student_ems.repository;

import com.kuangjia.student_ems.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Optional;

@Repository
public interface UserRepository extends JpaRepository<User, Long> {
    
    Optional<User> findByUsername(String username);
    
    boolean existsByUsername(String username);
    
    boolean existsByEmail(String email);

    List<User> findByDepartmentId(Long departmentId);
    
    long countByDepartmentId(Long departmentId);

    List<User> findByRole(User.UserRole role);
    
    boolean existsByPositionId(Long positionId);
    
    List<User> findByPositionId(Long positionId);
    
    long countByPositionId(Long positionId);

    @Query("SELECT u FROM User u LEFT JOIN FETCH u.department WHERE u.id = :id")
    Optional<User> findByIdWithDepartment(@Param("id") Long id);

    @Query(value = "SELECT u.id, u.username, u.name, u.email, u.phone, u.role, u.position_id, u.create_time, u.update_time, u.department_id, d.name as department_name FROM users u LEFT JOIN departments d ON u.department_id = d.id WHERE u.id = :id", nativeQuery = true)
    Object findUserWithDepartmentNameNative(@Param("id") Long id);
    
    @Query("SELECT u FROM User u LEFT JOIN FETCH u.department LEFT JOIN FETCH u.position WHERE " +
           "LOWER(u.username) LIKE LOWER(:keyword) OR " +
           "LOWER(u.name) LIKE LOWER(:keyword) OR " +
           "LOWER(u.email) LIKE LOWER(:keyword) OR " +
           "u.phone LIKE :keyword OR " +
           "(u.department IS NOT NULL AND LOWER(u.department.name) LIKE LOWER(:keyword))")
    List<User> searchUsers(@Param("keyword") String keyword);

    List<User> findByStatus(User.EmployeeStatus status);
} 